#!/usr/bin/php -q
<?PHP
/* Copyright 2023, IkerSaint
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License version 2,
 * as published by the Free Software Foundation.
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 */
?>
<?
$config_file = "/boot/config/plugins/zfs.master/zfs.master.cfg";
$docroot = "/usr/local/emhttp";
$plugin = "zfs.master";

require_once "$docroot/webGui/include/Wrappers.php";
require_once "$docroot/webGui/include/publish.php";

require_once $docroot."/plugins/".$plugin."/include/ZFSMHelpers.php";
require_once $docroot."/plugins/".$plugin."/backend/ZFSMOperations.php";

$zfsm_cfg = loadConfig(parse_plugin_cfg($plugin, true));
$zfsm_cfg['version'] = parse_ini_file('/etc/unraid-version')['version'];

$zfsm_cfg_timestamp = 0;

if (is_file($config_file) && is_readable($config_file)):
    $zfsm_cfg_timestamp = filemtime("/boot/config/plugins/zfs.master/zfs.master.cfg");
endif;

function getData($include_snapshots, $exclusion_pattern, $directory_listing, $ext) {
    $zpool_global = getZFSPools();
    $zpool_devices = array();
    $zpool_datasets = array();

    foreach ($zpool_global as $zpool):
        $zpool_name = $zpool['Pool'];

        $zpool_devices[$zpool_name] = getZFSPoolDevices($zpool_name);
        if ($include_snapshots):
            $zpool_datasets[$zpool_name] = getZFSPoolDatasetsAndSnapshots($zpool_name, $exclusion_pattern, $ext, $directory_listing);
            $zpool_global[$zpool_name]['Snapshots'] = $zpool_datasets[$zpool_name]['total_snapshots'];
        else:
            $zpool_datasets[$zpool_name] = getZFSPoolDatasets($zpool_name, $exclusion_pattern, $ext, $directory_listing);
        endif;
        $zpool_global[$zpool_name]['MountPoint'] = $zpool_datasets[$zpool_name]['mountpoint'];
    endforeach;

    $message = array();
    $message['data'] = array();
    $message['op'] = $include_snapshots ? "getAll" : "getDatasets";
    $message['data']['pools'] = $zpool_global;
    $message['data']['devices'] = $zpool_devices;
    $message['data']['datasets'] = $zpool_datasets;

    publish('zfs_master', json_encode($message));

    return $message;
}

function getAllData($exclusion_pattern, $directory_listing, $ext) {
    publish('zfs_master', '{"op":"start_refresh"}');

    $message = getData(true, $exclusion_pattern, $directory_listing, $ext);

    publish('zfs_master', '{"op":"stop_refresh"}');
}

function getDatasetsSnapshots($zpool, $zdatasets, $ext) {
    $message = array();
    $message['data'] = array();
    $message['op'] = "getSnapshot";
    $message['data']['pool'] = $zpool;

    foreach ($zdatasets as $zdataset):
        $message['data']['dataset'] = $zdataset;
        $message['data']['snapshots'] = getDatasetSnapshots($zpool, $zdataset['name'], $ext);

        publish('zfs_master', json_encode($message));

        getDatasetsSnapshots($zpool, $zdataset['child'], $ext);
    endforeach;
}

function getLazyLoadData($exclusion_pattern, $directory_listing, $ext) {
    publish('zfs_master', '{"op":"start_refresh"}');

    $message = getData(false, $exclusion_pattern, $directory_listing, $ext);

    foreach ($message['data']['datasets'] as $zpool):
        getDatasetsSnapshots($zpool['name'], $zpool['child'], $ext);
    endforeach;

    publish('zfs_master', '{"op":"stop_refresh"}');
}

function notifyConfigUpdate($config) {
    $message = array();
    $message['data'] = $config;
    $message['op'] = "updateConfig";

    publish('zfs_master', json_encode($message));
}

$sleep_time = 0.0;
$iters = 0;

while (true) {
    if ($iters > 15):
        if (is_file($config_file) && is_readable($config_file)):
            if (filemtime($config_file) != $zfsm_cfg_timestamp):
                $zfsm_cfg = loadConfig(parse_plugin_cfg($plugin, true));
                $zfsm_cfg['version'] = parse_ini_file('/etc/unraid-version')['version'];
                $zfsm_cfg_timestamp = filemtime("/boot/config/plugins/zfs.master/zfs.master.cfg");

                notifyConfigUpdate($zfsm_cfg);
            endif;
        endif;

        $iters = 0;
    endif;


    if ($zfsm_cfg['refresh_interval'] == 0 && file_exists('/tmp/zfsm_reload') == true):
        unlink('/tmp/zfsm_reload');

        if ($zfsm_cfg['lazy_load'] == "0"):
            getAllData($zfsm_cfg['dataset_exclusion'], $zfsm_cfg['directory_listing'], $zfsm_cfg['znapzend_data']);
        else:
            getLazyLoadData($zfsm_cfg['dataset_exclusion'], $zfsm_cfg['directory_listing'], $zfsm_cfg['znapzend_data']);
        endif;

    elseif (($zfsm_cfg['refresh_interval'] > 0 && $zfsm_cfg['refresh_interval'] <= $sleep_time) || file_exists('/tmp/zfsm_reload') == true):
        if (file_exists('/tmp/zfsm_reload')):
            unlink('/tmp/zfsm_reload');
        endif;

        if ($zfsm_cfg['lazy_load'] == "0"):
            getAllData($zfsm_cfg['dataset_exclusion'], $zfsm_cfg['directory_listing'], $zfsm_cfg['znapzend_data']);
        else:
            getLazyLoadData($zfsm_cfg['dataset_exclusion'], $zfsm_cfg['directory_listing'], $zfsm_cfg['znapzend_data']);
        endif;

        $sleep_time = 0.0;
    endif;

    usleep(150000); 
    $sleep_time += 0.15;
    $iters += 1;
}
?>